package com.woniuxy.mini;

import com.alipay.api.AlipayApiException;
import com.woniuxy.config.PayUtil;
import com.woniuxy.core.service.PaymentService;
import com.woniuxy.entity.OrderModel;
import com.woniuxy.entity.PaymentRecord;
import com.woniuxy.entity.ShopOrder;
import com.woniuxy.enums.ResponseEnum;
import com.woniuxy.feign.OrderApi;
import com.woniuxy.util.ResponseData;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 支付相关接口
 */
@Slf4j
@RestController
@RequestMapping("/pay")
public class PaymentController {
    @Autowired
    private PayUtil payUtil;
    private OrderModel orderModels = null;
    @Autowired
    private PaymentService paymentService;
    /**
     * 钱包创建支付订单
     */
    @PostMapping("/create")
    public ResponseData createPaymentOrder(@RequestBody PaymentRecord paymentRecord) {
        log.info("创建支付订单: {}", paymentRecord);
        // 调用支付服务创建订单
        ResponseData response = paymentService.createPaymentOrder(paymentRecord);
        // 记录操作结果
        log.info("支付订单创建结果: {}", response);
        return response;
    }
    /**
     * 查询支付结果
     */
    @GetMapping("/result/{transactionId}")
    public ResponseData<PaymentRecord> getPaymentResult(@PathVariable String transactionId) {
        log.info("查询支付结果: {}", transactionId);
        PaymentRecord record = paymentService.getPaymentRecord(transactionId);
        if (record == null) {
            return ResponseData.fail(ResponseEnum.PAYMENT_RECORD_NOT_FOUND);
        }
        return ResponseData.ok(record);
    }
    /**
     * 支付宝支付
     */
    @PostMapping("/alipay")
    public String alipay(@RequestBody OrderModel orderModel) throws AlipayApiException {
        orderModels = orderModel;
        BigDecimal orderPrice = orderModel.getOrderPrice();
        log.info("订单信息：{}", orderModel);
        /**
         参数1：订单号
         参数2：订单金额
         参数3：订单名称
         */
        return  payUtil.sendRequestToAlipay(orderModel.getOrderNumber(), orderPrice, orderModel.getIdleItem(),"mini");
    }

    //当我们支付完成之后跳转这个请求并携带参数，我们将里面的订单id接收到，通过订单id查询订单信息，信息包括支付是否成功等
    @PostMapping("/toSuccess")
    public String returns(@RequestParam("out_trade_no") String outTradeNo) {
        try {
            boolean paymentSuccess = paymentService.processPaymentResult(outTradeNo);

            if (paymentSuccess) {
                return "redirect:http://localhost:8081/#/paysuccess";
            } else {
                // 支付未成功或处理失败，可以返回失败页面或错误信息
                return "redirect:http://localhost:8081/#/payfail";
            }
        } catch (Exception e) {
            log.error("处理支付结果失败", e);
            return "redirect:http://localhost:8081/#/error";
        }
    }
    //调用支付宝沙箱钱包充值
    @GetMapping("/recharge")
    public String recharge(@RequestParam("out_trade_no") String outTradeNo,@RequestParam("money") BigDecimal money) throws AlipayApiException {
        String s = payUtil.sendRequestToAlipay(outTradeNo, money, "充值", "mini");
        return s;
    }
    //用户钱包退款
    @GetMapping("/refund/{orderId}")
    public ResponseData refund(@PathVariable("orderId") String orderId){
         paymentService.refund(orderId);
         return ResponseData.ok();
    }
}